<!--
 * @Author: firesky
 * @Date: 2020-08-31 09:49:57
 * @LastEditTime: 2020-11-04 09:57:23
 * @LastEditors: firesky
-->
<!-- 权限操作-->
<template>
  <div class="app-container">
    <br>
    <el-row>
      <el-col :span="6">
        <!-- 权限组 -->
        <el-table
          v-loading="listLoading"
          v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
          :data="userGroupList"
          element-loading-text="正在加载"
          border
          fit
          highlight-current-row
          @row-dblclick="allLimits"
          @current-change="userGroupCurrentChange">
          <el-table-column label="权限组序号" align="center">
            <template slot-scope="scope">
              {{ scope.row.rownumber }}
            </template>
          </el-table-column>
          <el-table-column label="权限组" align="center">
            <template slot-scope="scope">
              {{ scope.row.fname }}
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="5" :offset="1">
        <el-row>
          <el-row class="mb10">
            <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '新增').length" type="success" icon="el-icon-plus" @click="addGroup">新增</el-button>
          </el-row>
          <el-row class="mb10">
            <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '删除').length" type="success" icon="el-icon-delete" @click="deleteGroup">删除</el-button>
          </el-row>
          <el-row class="mb10">
            <el-button type="primary" icon="el-icon-plus" @click="userGroupAuthority('2', selectedLeftData)">权限</el-button>
          </el-row>
          <el-row class="mb10">
            <el-button type="primary" icon="el-icon-plus" @click="userGroupPublic('2', selectedLeftData)">公共字段设置</el-button>
          </el-row>

          <el-row class="mb10">
            <el-button type="primary" icon="el-icon-edit" @click="userGroupRename('2', selectedLeftData)">权限组重命名</el-button>
          </el-row>
          <!-- <el-row class="mb10">
            <el-button type="success" icon="el-icon-plus" @click="userGroupAddUser">权限组添加用户</el-button>
          </el-row> -->

        </el-row>
      </el-col>
    </el-row>

    <!-- 添加用户组 -->
    <el-dialog v-el-drag-dialog :visible.sync="isShowUserGroup" title="添加／编辑">
      <el-form v-loading="loadingUserGroupForm" ref="userGroupForm" :rules="userGroupRules" :model="userGroupForm" label-width="140px">
        <el-form-item label="用户组名称" prop="groupname">
          <el-input v-model="userGroupForm.groupname"/>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loadingUserGroupForm" type="primary" @click="addUserGroup" >确认</el-button>
          <el-button @click="isShowUserGroup=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 用户组添加用户 -->
    <!-- <el-dialog v-el-drag-dialog :visible.sync="isShowUser" title="添加／编辑" >
      <el-form v-loading="loadingUserForm" ref="userForm" :rules="userRules" :model="userForm" style="width: 100%;" label-width="140px">
        <el-form-item label="用户名" prop="userids" style="width: 100%;">
          <el-select v-model="userForm.userids" placeholder="请选择" multiple clearable filterable>
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.username"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="用户组" prop="groupid" style="width: 100%;">
          <el-select v-model="userForm.groupid" placeholder="请选择" clearable filterable>
            <el-option
              v-for="item in userGroupList"
              :key="item.id"
              :label="item.fname"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loadingUserForm" type="primary" @click="addUser" >确认</el-button>
          <el-button @click="isShowUser=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog> -->

    <!-- 用户组对应权限 -->
    <el-dialog v-el-drag-dialog :visible.sync="isShowUserGroupAuthority" title="用户组对应权限">
      <div class="userGroupAuthority">
        <el-tree :data="authorityData" :props="defaultProps" @node-click="handleNodeClick"/>
      </div>

    </el-dialog>
    <!-- 权限菜单详情 -->
    <el-dialog v-el-drag-dialog :visible.sync="isMenuDetailShow" :title="menuDetailTitle + '  ' + '    添加／编辑'">
      <el-form v-loading="loadingMenuDetail" ref="menuDetailForm" :rules="menuDetailRules" :model="menuDetailForm" label-width="140px">

        <el-checkbox :indeterminate="isIndeterminate" v-model="menuDetailForm.checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"/>
        <el-checkbox-group v-model="menuDetailForm.selectedAuth" @change="selectLimitChange">
          <el-checkbox v-for="item in allOptionsList" :label="item.FName" :key="item.FAccessMask">{{ item.FName }}</el-checkbox>
        </el-checkbox-group>
        <div style="margin: 15px 0;"/>

        <el-form-item>
          <el-button :loading="loadingMenuDetail" type="primary" @click="menuDetailConfirm" >确认</el-button>
          <el-button @click="isMenuDetailShow=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 穿梭框 -->
    <el-dialog v-el-drag-dialog :visible.sync="isShowTransferAuthority" :title="'权限组 ' + selectedLeftData.fname" >
      <el-transfer
        :titles="['已选', '未选']"
        :props="{
          key: 'userid',
          label: 'username'
        }"
        v-model="rightKey"
        :data="allData"
        @change="handleChange"/>
      <br>
      <el-button type="success" icon="el-icon-plus" @click="allLimitsConfirm">确认</el-button>
    </el-dialog>

    <!-- 公共设置 -->
    <el-dialog v-el-drag-dialog :visible.sync="isShowuserGroupPublic" :before-close="userGroupPublicQX" title="公共字段设置" width="30%">
      <div >
        <template>
          <el-table
            ref="multipleTable"
            :data="tableData"

            style="width: 100%"
            border
            align="center"
            @selection-change="handleSelectionChange">

            <el-table-column

              type="index"
              align="center"
              width="50"/>

            <el-table-column
              label="权限功能说明"
              align="center"
            >
              <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>

            <el-table-column

              :reserve-selection="true"
              type="selection"
              align="center"
              width="65"/>
          </el-table>

        </template>
        <div slot="footer" style="margin: 0 auto;width:200px; margin-top: 10px;">
          <el-button type="primary" @click="userGroupPublicQR">确 定</el-button>
          <el-button @click="userGroupPublicQX">取 消</el-button>

        </div>
      </div>

    </el-dialog>

  </div>
</template>
<script>
let opername = ''
import { menu, menuDetail, createGroup, groupList, delGroup, userToGroup, admin, groupData, sqInsert, groupToQXDetail, accessField, getaccessField } from '../../api/account'
import { common } from '../../mixins/common'
import { pagination } from '../../mixins/pagination'
export default {
  mixins: [common, pagination],
  data() {
    return {
      opername: '',
      listLoading: false,

      // 弹窗
      isShowUserGroup: false,
      loadingUserGroupForm: false,
      userGroupForm: {
        groupname: '',
        id: 0

      },
      userGroupRules: {
        groupname: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ]
      },

      userGroupList: [],
      selectedLeftData: '',

      // 用户组添加用户
      isShowUser: false,
      loadingUserForm: false,
      userForm: {
        userids: [],
        groupid: ''
      },
      userRules: {
        userids: [
          { required: true, message: '请输入用户名', trigger: 'change' }
        ],
        groupid: [
          { required: true, message: '请输入用户组', trigger: 'change' }
        ]
      },

      listUserLoading: false,
      userList: [], // 用户列表

      // 用户组下所有用户
      userGroupUserList: [], // 已经分类的用户
      isShowUserGroupUser: false,

      // 用户组公共设置
      isShowuserGroupPublic: false,

      // 用户组对应权限
      isShowUserGroupAuthority: false,
      type: 2, // 默认用户组权限  用户权限1， 组权限2
      fuserid: '', // type为2取组id，type为1取用户id
      authorityData: [],
      defaultProps: {
        children: 'child',
        label: 'fname'
      },

      // 权限菜单详情
      isMenuDetailShow: false,
      loadingMenuDetail: false,
      menuDetailForm: {
        checkAll: false,
        selectedAuth: []
      },
      menuDetailRules: {

      },
      menuDetailTitle: '', // 标题

      // checkAll: false,
      // selectedAuth: [],
      isIndeterminate: true,
      optionsList: [],
      allOptionsList: [],
      fobjectid: '',
      fobjecttype: '',
      faccessmask: '', // 求和,
      fsqlist: '',

      // 穿梭框
      isShowTransferAuthority: false,
      rightKey: [], // 右侧未选列表key值
      leftKey: [], // 过滤后左侧的值
      allData: [],
      groupid: '',
      leftid: [], // 左侧选中

      // 用户菜单
      menusList: [],
      limits: [],
      userKey: '',

      tableDataR: [{
        name: '重要字段查看FldView1',
        FObjectType: 96000,
        FObjectID: 60001,
        FFunc: 'FldView1',
        FIndex: 1
      }, {
        name: '重要字段查看FldView2',
        FObjectType: 96000,
        FObjectID: 60001,
        FFunc: 'FldView2',
        FIndex: 2

      }],

      tableData: [{
        name: '重要字段查看FldView1',
        FObjectType: '96000',
        FObjectID: 60001,
        FFunc: 'FldView1',
        FIndex: 1
      }, {
        name: '重要字段查看FldView2',
        FObjectType: '96000',
        FObjectID: 60001,
        FFunc: 'FldView2',
        FIndex: 2

      }, {
        name: '重要字段查看FldView3',
        FObjectType: '96000',
        FObjectID: 60001,
        FFunc: 'FldView3',
        FIndex: 3
      }, {
        name: '重要字段查看FldView4',
        FObjectType: '96000',
        FObjectID: 60001,
        FFunc: 'FldView4',
        FIndex: 4
      }, {
        name: '重要字段查看FldView5',
        FObjectType: '96000',
        FObjectID: 60001,
        FFunc: 'FldView5',
        FIndex: 5
      }, {
        name: '重要字段查看FldView6',
        FObjectType: '96000',
        FObjectID: 60001,
        FFunc: 'FldView6',
        FIndex: 6
      }, {
        name: '重要字段查看FldView7',
        FObjectType: '96000',
        FObjectID: 60001,
        FFunc: 'FldView7',
        FIndex: 7
      }, {
        name: '重要字段查看FldView8',
        FObjectType: '96000',
        FObjectID: 60001,
        FFunc: 'FldView8',
        FIndex: 8
      }],
      multipleSelection: [],
      tableData3: []

    }
  },
  async mounted() {
    this.userKey = this.$route.meta.FRepKey
    opername = decodeURIComponent(this.globalDb.fname)
    this.opername = decodeURIComponent(this.globalDb.fname)
    await this.getAdmin()
    await this.getGroupList()
  },
  methods: {
    // 组权限详情显示
    async getGroupToQXDetail(FObjectType, FObjectID, FGroupID) {
      try {
        const res = await groupToQXDetail({
          db: this.globalDb.db,
          opername,
          FObjectType,
          FObjectID,
          FGroupID
        })
        return res
      } catch (error) {
        // console.log(error)
      }
    },
    handleChange(value, direction, movedKeys) {
      // value值是移动后右边的数组
      const arr = this.allData.filter(it => value.every(item => item !== it.userid))
      this.leftKey = arr.map(it => it.userid)
    },
    // 双击
    async allLimits() {
      this.allData = []
      this.userGroupUserList = []
      this.rightKey = []

      const groupname = this.selectedLeftData.fname
      this.groupid = this.selectedLeftData.id
      const res = await groupData({
        db: this.globalDb.db,
        opername,
        groupname
      })
      if (res.Error === 0) {
        this.isShowTransferAuthority = true
        const leftArr = res.Data.yydata // 已选中
        const rightArr = res.Data.wydata // 未选中
        this.allData = rightArr.concat(leftArr) // 所有数据
        this.rightKey = rightArr.map(it => it.userid) // 未选数据userid值
        this.leftKey = leftArr.map(it => it.userid) // 已选数据userid值
      }
    },
    async allLimitsConfirm() {
      try {
        const res = await userToGroup({
          db: this.globalDb.db,
          opername,
          userids: this.leftKey.join(','),
          groupid: this.groupid
        })

        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
          this.isShowTransferAuthority = false
        }
      } catch (error) {
        // console.log(error)
      }
    },
    /* 权限组重命名*/
    async userGroupRename(type, data) {
      if (!data && !data.id) {
        this.$message({
          message: '请选择左侧权限组',
          type: 'error'
        })
        return
      }

      if (data.fname === '系统管理员组') {
        this.$message({
          message: '系统管理员组不能修改',
          type: 'error'
        })
        return
      }

      this.userGroupForm = {}
      const dataT = {
        groupname: data.fname,
        id: data.id
      }
      for (const i in dataT) {
        this.$set(this.userGroupForm, i, dataT[i])
      }

      setTimeout(() => {
        this.$refs['userGroupForm'].clearValidate()
      })

      this.isShowUserGroup = true
    },

    async userGroupAuthority(type, data) {
      if (!data && !data.id) {
        this.$message({
          message: '请选择用户组/用户',
          type: 'error'
        })
        return
      }
      this.getMenu()
      this.type = type
      this.fuserid = data.id
      this.isShowUserGroupAuthority = true
    },

    // 公共设置
    async userGroupPublic(type, data) {
      if (!data && !data.id) {
        this.$message({
          message: '请选择左侧权限组',
          type: 'error'
        })
        return
      }

      this.isShowuserGroupPublic = true
      const res = await getaccessField({
        db: this.globalDb.db,
        opername,
        id: data.id
      })
      this.tableData3 = []
      if (res.Data.length > 0) {
        this.tableData3 = res.Data
        this.tableData3.forEach(row => {
          this.$nextTick(function() {
            this.$refs.multipleTable.toggleRowSelection(this.tableData[row.FIndex - 1], true)
          })
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },

    // 公共设置  -- 取消 ×
    userGroupPublicQX() {
      this.isShowuserGroupPublic = false
      this.$refs.multipleTable.clearSelection()
    },

    // 公共设置-- 选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 公共设置-- 选择确认
    async userGroupPublicQR() {
      // if (this.multipleSelection.length < 1) {
      //   this.$message({
      //     message: '没有勾选一行',
      //     type: 'error'
      //   })
      //   return
      // }
      try {
        const res = await accessField({
          db: this.globalDb.db,
          opername,
          select: this.multipleSelection,
          selectedLeftData: this.selectedLeftData

        })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
          this.isShowuserGroupPublic = false
          this.$refs.multipleTable.clearSelection()
        }
      } catch (error) {
        // console.log(error)
      }
    },

    // 公共设置 --表格选择
    selectFuc(row, index) {
      if (index === 1) {
        return index
      }
    },

    async getMenu() {
      try {
        const res = await menu({
          opername: decodeURIComponent(this.globalDb.fname),
          db: this.globalDb.db
        })
        this.authorityData = res.Data
      } catch (error) {
        // console.log(error)
      }
    },
    async handleNodeClick(data) {
      this.fobjectid = ''
      this.fobjecttype = ''
      this.faccessmask = 0
      this.menuDetailTitle = data.fdescription

      this.optionsList = []
      this.menuDetailForm.selectedAuth = []
      // this.$set(this.menuDetailForm, 'selectedAuth', [])
      this.menuDetailForm.checkAll = false
      this.fobjectid = data.fobjectid
      this.fobjecttype = data.fobjecttype
      if (!data.child) {
        this.isMenuDetailShow = true
        try {
          const res = await menuDetail({
            db: this.globalDb.db,
            opername,
            fobjectid: this.fobjectid,
            fobjecttype: this.fobjecttype
          })

          res.Data.map(item => {
            this.optionsList.push(item.FName)
          })
          this.allOptionsList = res.Data

          const resGroup = await this.getGroupToQXDetail(this.fobjecttype, this.fobjectid, this.fuserid)

          this.menuDetailForm.selectedAuth = resGroup.Data.map(it => it.FName)
          this.selectLimitChange(this.menuDetailForm.selectedAuth)
        } catch (error) {
          // console.log(error)
        }
      }
    },
    // 全选/全不选
    handleCheckAllChange(val) {
      let sum = ''
      this.allOptionsList.map(item => {
        sum = !sum ? 0 : sum
        sum += parseInt(item.FAccessMask)
      })
      this.menuDetailForm.selectedAuth = val ? this.optionsList : []
      this.isIndeterminate = false
      this.faccessmask = val ? sum : 0

      this.fsqlist = this.allOptionsList.filter(it => this.menuDetailForm.selectedAuth.some(item => item === it.FName)).map(it => it.FAccessMask).join(',')
    },
    selectLimitChange(value) {
      let sum = 0
      const checkedCount = value.length
      this.menuDetailForm.checkAll = checkedCount === this.allOptionsList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allOptionsList.length

      this.allOptionsList.map(item => {
        value.map(it => {
          if (item.FName === it) {
            sum += parseInt(item.FAccessMask)
          }
        })
        this.faccessmask = sum
      })
      this.fsqlist = this.allOptionsList.filter(it => this.menuDetailForm.selectedAuth.some(item => item === it.FName)).map(it => it.FAccessMask).join(',')
    },
    menuDetailConfirm() {
      this.$refs['menuDetailForm'].validate(async(valid) => {
        if (valid) {
          try {
            this.loadingMenuDetail = true
            const res = await sqInsert({
              db: this.globalDb.db,
              opername,
              type: this.type,
              fuserid: this.fuserid,
              fobjectid: this.fobjectid,
              fobjecttype: this.fobjecttype,
              faccesstype: 1,
              faccessmask: this.faccessmask,
              fsqlist: this.fsqlist
            })

            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              this.isMenuDetailShow = false
              this.loadingMenuDetail = false
            }
          } catch (error) {
            this.loadingMenuDetail = false
          }
        } else {
          return false
        }
      })
    },
    async addGroup() {
      this.userGroupForm = {}
      const data = {
        groupname: '',
        id: 0
      }
      for (const i in data) {
        this.$set(this.userGroupForm, i, data[i])
      }

      setTimeout(() => {
        this.$refs['userGroupForm'].clearValidate()
      })

      this.isShowUserGroup = true
    },
    async addUserGroup() {
      if (this.userGroupForm.groupname === '系统管理员组') {
        this.$message({
          message: '系统管理员组不能新增，已存在',
          type: 'error'
        })
        return
      }

      this.$refs['userGroupForm'].validate(async(valid) => {
        if (valid) {
          try {
            this.loadingUserGroupForm = true
            const res = await createGroup({
              db: this.globalDb.db,
              opername,
              groupname: this.userGroupForm.groupname,
              id: this.userGroupForm.id
            })
            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              this.isShowUserGroup = false
              this.loadingUserGroupForm = false
              this.getGroupList()
              this.selectedLeftData = ''
            }
          } catch (error) {
            this.loadingUserGroupForm = false
          }
        } else {
          return false
        }
      })
    },
    async getGroupList() {
      try {
        const res = await groupList({
          opername: decodeURIComponent(this.globalDb.fname),
          db: this.globalDb.db
        })
        this.userGroupList = res.Data
        const menuRes = JSON.parse(localStorage.getItem('setMenuData'))
        this.menusList = menuRes
        if (menuRes.length >= 1) {
          menuRes.map(it => {
            it.children.map(item => {
              if (item.fobjectid === this.userKey) {
                this.$set(this, 'limits', item.child)
              }
            })
          })
        }
      } catch (error) {
        // console.log(error)
      }
    },
    async deleteGroup() {
      if (!this.selectedLeftData && !this.selectedLeftData.id) {
        this.$message({
          message: '请选择要删除的组名',
          type: 'error'
        })
        return
      }
      if (this.selectedLeftData.fname === '系统管理员组') {
        this.$message({
          message: '不能删除系统管理员组',
          type: 'error'
        })
        return
      }

      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning'
      }).then(async() => {
        const id = this.selectedLeftData.id
        const res = await delGroup({
          db: this.globalDb.db,
          opername,
          data: this.selectedLeftData,
          groupname: this.selectedLeftData.fname,
          id
        })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
          this.getGroupList()
          this.selectedLeftData = ''
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    userGroupCurrentChange(val) {
      if (val) {
        this.selectedLeftData = val
      }
    },
    async userGroupAddUser() {
      this.userForm = {}
      const data = {
        userids: [],
        groupid: ''

      }
      for (const i in data) {
        this.$set(this.userForm, i, data[i])
      }
      setTimeout(() => {
        this.$refs['userForm'].clearValidate()
      })

      this.isShowUser = true
    },

    async addUser() {
      this.$refs['userForm'].validate(async(valid) => {
        if (valid) {
          try {
            this.loadingUserForm = true
            const res = await userToGroup({
              db: this.globalDb.db,
              opername,
              userids: this.userForm.userids.join(','),
              groupid: this.userForm.groupid
            })

            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              this.isShowUser = false
              this.loadingUserForm = false
            }
          } catch (error) {
            this.loadingUserForm = false
          }
        } else {
          return false
        }
      })
    },
    // 用户组列表
    async getAdmin() {
      try {
        this.listUserLoading = true
        const res = await admin({
          db: this.globalDb.db,
          opername: decodeURIComponent(this.globalDb.fname),
          keyword: this.keyword,
          limit: this.pagesize ? this.pagesize : 1000,
          page: this.currentPage
        })
        this.userList = res.result

        this.listUserLoading = false
      } catch (error) {
        this.listUserLoading = false
      }
    }
    /** *********************以下为用户************************** */

  }
}
</script>
<style lang="scss" scoped>
  $dark_gray:#889aa4;
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .mb10 {
    margin-bottom: 10px;
  }
  .userGroupAuthority {
    min-height: 320px;
  }
</style>
